<?php

namespace ltcms\session;

/**
 * session 操作
 * Class Sessions
 */
class Sessions
{
    protected $resource=0;
    protected $initNums=0;
    protected $driver = LTCMS_SESSION_DRIVER?LTCMS_SESSION_DRIVER:"file";
    private static $_instance;

    private function __construct(){
        $this->_init();
    }
    private function __clone(){ }

    /**
     * 获取类对象
     */
    public static  function getInstance(){
        if(!(self::$_instance instanceof self)){
            self::$_instance=new self();
        }
        return self::$_instance;
    }

    /**
     * 初始化对象
     */
    public function _init()
    {
        if($this->initNums ==0){
            if($this->driver=="file"){
                include_once __DIR__."/Sessions_file.php";
                new Sessions_file();
                $this->initNums++;
            }else if($this->driver=="mysql"){
                include_once __DIR__."/Sessions_mysql.php";
                $this->initNums++;
            }else{
                throw new \Exception("session:{$this->driver} 驱动不存在");
            }
        }
    }

    /**
     * 返回所有 sessionId
     * @return mixed
     */
    public function sessionId(){
        return session_id();
    }

    /**
     * 删除 by sessionId
     * @return mixed
     */
    public function delBySessionId($sid){
        if($this->driver=="file"){
            //删除文件
            $dir = LTCMS_SESSION_DIR."/".strtolower(substr(md5(LTCMS_KEY), 2, 6)).'/';
            $file=$dir."sess_{$sid}";
            if(is_file($file)){
                unlink($file);
            }
        }else if($this->driver=="mysql"){
            //删除数据
            $tbPre=Db()->getConfig()["tb_pre"];
            $sql="delete from {$tbPre}sessions where sid='{$sid}'";
            Db()->execute($sql);
        }
    }

    /**
     * 返回所有 session
     * @return mixed
     */
    public function all(){
        return $_SESSION;
    }

    /**
     * 获取 session 数据
     */
    public function get($key,$default=NULL)
    {
        return isset($_SESSION[$key])?$_SESSION[$key]:$default;
    }

    /**
     * 是否存在 session 数据
     */
    public function has($key)
    {
        return isset($_SESSION[$key])?true:false;
    }

    /**
     * 设置 session 数据
     */
    public function set($key,$val)
    {
        return $_SESSION[$key]=$val;
    }

    /**
     * 删除 session 数据
     */
    public function delete($key)
    {
        if($key){
            unset($_SESSION[$key]);
        }
    }

    /**
     * 清除 session 数据
     */
    public function clear()
    {
        $_SESSION = [];
    }
}

